package lowijs.XfDroid;

import java.text.*;
import java.util.*;

import android.app.*;
import android.content.*;
import android.os.*;
import android.preference.*;
import android.text.*;
import android.view.*;
import android.widget.*;

import lowijs.XfireClient.*;
import lowijs.XfireClient.event.*;

public class ConvoWindow extends Activity implements XfireObserver {
	private final int CW_REFRESHLIST = 1;
	private final int CW_TOGGLE_ENABLED = 2;
	
	private Friend f = null;
	private ConvoWindowAdapter adapter = null;
	
	private ListView lv = null;
	private Button btSend = null;
	private EditText etMessage = null;
	private SharedPreferences prefs = null;
	
	public void onCreate(Bundle b) {
		super.onCreate(b);
		setContentView(R.layout.convowindow);
		
		btSend = (Button)findViewById(R.id.btSend);
		etMessage = (EditText)findViewById(R.id.etMessage);
		
		byte[] userid = getIntent().getExtras().getByteArray("friend");
		f = FriendManager.getInstance().getFriendByUserid(userid);
		
		adapter = new ConvoWindowAdapter(this, R.layout.convoline, f.getConversation());
		lv = (ListView)findViewById(R.id.lvConversation);
		lv.setAdapter(adapter);
		
		View.OnClickListener sendListener = new View.OnClickListener() {
			public void onClick(View v) {
				sendIM();
			}
		};
		btSend.setOnClickListener(sendListener);
		
		TextView.OnEditorActionListener actionListener =
			new TextView.OnEditorActionListener() {
				public boolean onEditorAction(TextView v, int actionId,
						KeyEvent event) {
					if (etMessage.length() != 0 &&
							prefs.getBoolean("XfDroid.sendOnEnter", true))
						sendIM();
					return true;
				}
			};

		TextWatcher textWatcher = new TextWatcher() {
			public void onTextChanged(CharSequence s, int start, int before,
					int count) {
					btSend.setEnabled(s.length() != 0);
			}
			
			public void beforeTextChanged(CharSequence s, int start, int count,
					int after) {
				
			}
			
			public void afterTextChanged(Editable s) {
				
			}
		};	
		
		etMessage.setOnEditorActionListener(actionListener);
		etMessage.addTextChangedListener(textWatcher);
		etMessage.requestFocus();
		
		Message m = Message.obtain(cwHandler, CW_TOGGLE_ENABLED);
		cwHandler.sendMessage(m);
		
		prefs = PreferenceManager.getDefaultSharedPreferences(this);
	}
	
	public void onResume() {
		super.onResume();
		XfDroidService.sendNoNotificationsFor(f);
	}
	
	public void onStart() {
		super.onStart();
		EventManager.addObserver(this);
		Message m = Message.obtain(cwHandler, CW_REFRESHLIST);
		cwHandler.sendMessage(m);
	}
	
	public void onPause() {
		super.onPause();
		XfDroidService.sendAllNotifications();
	}
	
	public void onStop() {
		super.onStop();
		EventManager.removeObserver(this);
	}
	
	private void sendIM() {
		EditText etMessage = (EditText)findViewById(R.id.etMessage);
		f.sendIM(etMessage.getText().toString());
		
		etMessage.setText("");
	}
	
	public void handleEvent(XfireEvent event) {
		Message m;
		
		switch(event.getEventType()) {
		case XfireEvent.XF_RECVIM:
			ReceiveImEvent e = (ReceiveImEvent)event;
			
			if (e.getFriend() != f)
				return;
		case XfireEvent.XF_SENDIM:
			m = Message.obtain(cwHandler, CW_REFRESHLIST);
			cwHandler.sendMessage(m);
			return;
		case XfireEvent.XF_DCREASON:
			Intent i = new Intent(this, Login.class);
			i.putExtra("disconnected", true);
			startActivity(i);
			finish();
			return;
		case XfireEvent.XF_FRSTATUS:
			FriendEvent fse = (FriendEvent)event;
			if (fse.getFriend() == f) {
				m = Message.obtain(cwHandler, CW_TOGGLE_ENABLED);
				cwHandler.sendMessage(m);
			}
			return;
		}
	}
	
	private Handler cwHandler = new Handler() {
		public void handleMessage(Message m) {
			switch(m.what) {
			case CW_REFRESHLIST:
				adapter.notifyDataSetChanged();
				lv.setSelection(lv.getCount() - 1);
				String convo_with = getString(R.string.convo_with);
				setTitle("XfDroid : " + convo_with + " "
						+ f.getNick());
				return;
			case CW_TOGGLE_ENABLED:
				boolean enable = f.isOnline();
				btSend.setEnabled(etMessage.length() != 0 && enable);
				etMessage.setEnabled(enable);
			}
		}
	};
	
	private class ConvoWindowAdapter extends ArrayAdapter<IM> {
		public ConvoWindowAdapter(Context context, int textViewResourceId,
				List<IM> objects) {
			super(context, textViewResourceId, objects);
		}

		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
            if (v == null) {
                LayoutInflater li = (LayoutInflater)getSystemService(
                                Context.LAYOUT_INFLATER_SERVICE);
                v = li.inflate(R.layout.convoline, null);
            }

            IM im = getItem(position);
            
            TextView tvTime = (TextView)v.findViewById(R.id.tvTime);
            TextView tvNickname = (TextView)v.findViewById(R.id.tvNickname);
            TextView tvMessage = (TextView)v.findViewById(R.id.tvMessage);
            
            SimpleDateFormat date = new SimpleDateFormat("HH:mm");
            
            tvTime.setText("[" + date.format(im.getDate()) + "]");
            if (im.getName() == null)
            	tvNickname.setText(XfDroidService.getXfireClient()
            			.getNickname());
            else
            	tvNickname.setText(im.getName());
            tvMessage.setText(im.getMessage());
            
            return v;
		}
	}
}
